package com.xsystem.api.util;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class IpRange {

	private static final int BYTES_LEN = 16;
	private byte[] startIp;
	private byte[] endIp;

	// Single IP
	public IpRange(String singleIp) throws UnknownHostException {
		this.startIp = getBytes(singleIp);
		this.endIp = null;
	}

	// A range of IPs
	public IpRange(String startIp, String endIp) throws UnknownHostException {
		this.startIp = getBytes(startIp);
		this.endIp = getBytes(endIp);
	}

	public boolean isIpWithinRange(String ip) throws UnknownHostException {
		byte[] checkIp = getBytes(ip);

		if (endIp == null) { // Compare against a single IP
			for (int i = 0; i < BYTES_LEN; i++) {
				if (checkIp[i] != startIp[i]) {
					return false;
				}
			}
		} else { // Compare against a range of IPs
			for (int i = 0; i < BYTES_LEN; i++) {
				if (checkIp[i] < startIp[i] || checkIp[i] > endIp[i]) {
					return false;
				}
			}
		}
		return true;
	}

	private byte[] getBytes(String ip) throws UnknownHostException {
		// convert IPv4 address to IPv6 format
		if (!ip.contains(":")) {
			ip = "::" + ip;
		}
		InetAddress inetAddress = InetAddress.getByName(ip);
		byte[] ret = inetAddress.getAddress();
		if (ret.length != BYTES_LEN) {
			throw new UnknownHostException("Invalid byte length " + ret.length);
		}
		return ret;
	}
}
